<template>
    <div>
        <!-- 面包屑 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片 -->
        <el-card>
            <!-- 警告 -->
            <el-alert show-icon title="只允许为第三级分类设置参数" type="warning" :closable="false"></el-alert>
            <el-row class="cate-opt">
              <el-col>
                  <span>选择商品分类：</span>
                  <!-- 级联参数选择框 -->
                  <el-cascader v-model="selectedCateKeys" :options="catelist" :props="cateListProp" @change="handleChange"></el-cascader>
              </el-col>
            </el-row>
            <!-- Tab 标签 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 动态参数页签 -->
                <el-tab-pane label="动态参数" name="many">
                    <!-- 添加参数按钮 -->
                    <el-button type="primary" size="mini" :disabled="isDisabledBtn" @click="addDialogVisible = true">添加参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyTableData" border stripe >
                        <el-table-column type="expand">
                            <!-- 渲染可选项标签 -->
                            <template slot-scope="scope">
                                <el-tag type="primary" closable v-for="(item, index) in scope.row.attr_vals" :key="index" @close="handleTagClose(index, scope.row)">{{item}}</el-tag>
                                <!-- 文本输入框-->
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParam(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 静态属性页签 -->
                <el-tab-pane label="静态属性" name="only">
                    <!-- 添加属性按钮 -->
                    <el-button type="primary" size="mini" :disabled="isDisabledBtn" @click="addDialogVisible = true">添加属性</el-button>
                    <!-- 静态属性表格 -->
                    <el-table :data="onlyTableData" border stripe >
                        <el-table-column type="expand">
                            <!-- 渲染可选项标签 -->
                            <template slot-scope="scope">
                                <el-tag type="primary" closable v-for="(item, index) in scope.row.attr_vals" :key="index" @close="handleTagClose(index, scope.row)">{{item}}</el-tag>
                                <!-- 文本输入框-->
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParam(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加参数对话框 -->
        <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
            <!-- 添加参数表单 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParam">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改参数对话框 -->
        <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
            <!-- 添加参数表单 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParam">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data () {
        return {
            // 商品分类列表
            catelist: [],
            // 级联选择框配置属性
            cateListProp: {
                value: 'cat_id',
                label: 'cat_name',
                childern: 'children',
                expandTrigger: 'hover'
            },
            // 级联选择框选中ID数组
            selectedCateKeys: [],
            // Tab 激活的页签
            activeName: 'many',
            // 动态参数数据
            manyTableData: [],
            // 静态属性数据
            onlyTableData: [],
            // 添加参数对话框控制显示
            addDialogVisible: false,
            // 添加参数表单对象
            addForm: {
                attr_name: '' // 参数名称
            },
            // 添加参数表单验证规则
            addFormRules: {
                attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
            },
            // 修改参数对话框显示控制
            editDialogVisible: false,
            // 修改参数表单验证规则
            editFormRules: {
                attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
            },
            // 修改参数表单对象
            editForm: {
                attr_name: '' // 参数名称
            }
        }
    },
    created () {
        this.getCateList()
    },
    methods: {
        // 获取商品分类列表
        async getCateList () {
            const { data: res } = await this.$http.get('categories')
            if (res.meta.status !== 200) {
                return this.$msg.error('获取商品分类失败')
            }
            this.catelist = res.data
        },
        // 级联选择框变化事件
        handleChange () {
            this.getParamsData()
        },
        // 点击页签事件
        handleTabClick () {
            this.getParamsData()
        },
        // 获取参数列表
        async getParamsData () {
            // 如果选中的不是三级分类。清空级联选择器值和列表数据
            if (this.selectedCateKeys.length !== 3) {
                this.selectedCateKeys = []
                this.manyTableData = []
                this.onlyTableData = []
                return
            }
            // 选中的是三级分类
            // 根据分类ID和选中面板或者参数列表
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
            if (res.meta.status !== 200) {
                return this.$msg.error('获取参数列表失败')
            }
            // 遍历可选项
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                // 为每一行数据提供显示与隐藏输入框的属性
                item.inputVisible = false
                item.inputValue = ''
            })
            // 给tab页签下表格赋值
            if (this.activeName === 'many') {
                this.manyTableData = res.data
            } else {
                this.onlyTableData = res.data
            }
        },
        // 添加参数对话框关闭事件
        addDialogClose () {
            this.$refs.addFormRef.resetFields()
        },
        // 添加参数
        addParam () {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
                    attr_name: this.addForm.attr_name,
                    attr_sel: this.activeName
                })
                if (res.meta.status !== 201) {
                    return this.$msg.error('添加参数失败')
                }
                this.$msg.success('添加参数成功')
                this.addDialogVisible = false
                this.getParamsData()
            })
        },
        // 展示编辑参数对话框
        async showEditDialog (attrId) {
            // 根据ID查询参数
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, {
                params: {
                    attr_sel: this.activeName
                }
            })
            if (res.meta.status !== 200) return this.$msg.error('根据ID查询参数失败')
            // 查询结果保存到编辑表单对象中
            this.editForm = res.data
            this.editDialogVisible = true
        },
        // 修改参数对话框关闭事件
        editDialogClose () {
            this.$refs.editFormRef.resetFields()
        },
        // 编辑参数
        editParam () {
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
                    attr_name: this.editForm.attr_name,
                    attr_sel: this.activeName
                })
                if (res.meta.status !== 200) return this.$msg.error('更新参数失败')
                this.$msg.success('更新成功')
                this.getParamsData()
                this.editDialogVisible = false
            })
        },
        // 删除参数
        deleteParam (attrId) {
            this.$confirm('此操作将永久删除参数, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
                if (res.meta.status !== 200) return this.$msg.error('删除参数失败')
                this.getParamsData()
                this.$msg({
                    type: 'success',
                    message: '删除成功!'
                })
            }).catch(() => {
                this.$msg({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        //  文本输入框失去焦点或者摁下enter键触发
        handleInputConfirm (row) {
            // 隐藏输入框
            if (row.inputValue.trim().length === 0) {
                row.inputValue = ''
                row.inputVisible = false
                return
            }
            // 输入内容正确，将新可选项编辑到当前参数中
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue = ''
            // 保存参数项修改
            this.saveAttrVals(row)
        },
        // 隐藏添加按钮，显示文本输入框
        // $nextTick 单页面控件渲染完毕后才执行回调函数
        showInput (row) {
            row.inputVisible = true
            // input 自动对焦
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus()
            })
        },
        async saveAttrVals (row) {
            // 编辑可选项请求
            const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
                {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                }
            )
            if (res.meta.status !== 200) {
                return this.$msg.error('修改参数项失败')
            }
            this.$msg.success('修改参数项成功')
        },
        // 删除参数可选项
        handleTagClose (index, row) {
            row.attr_vals.splice(index, 1)
            this.saveAttrVals(row)
        }
    },
    computed: {
        // 添加属性和添加属性按钮控制
        isDisabledBtn () {
            return this.selectedCateKeys.length !== 3
        },
        // 返回商品ID
        cateId () {
            if (this.selectedCateKeys.length === 3) {
                return this.selectedCateKeys[2]
            }
            return null
        },
        // 动态计算对话框标题
        titleText () {
            return this.activeName === 'many' ? '动态参数' : '静态属性'
        }
    }
}
</script>

<style lang="less" scoped>
.cate-opt {
    margin: 15px 0;
}

.el-tag {
    margin: 5px;
}

.input-new-tag {
    width: 120px;
}
</style>
